package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"store/models"
)

type StoreController struct {
	beego.Controller
}

func (c *StoreController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	address := c.GetString("address")
	tel := c.GetString("tel")
	store := models.Store{
		Name:    name,
		Address: address,
		Tel:     tel,
	}
	err := models.DB.Create(&store).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *StoreController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var store []models.Store
	err := models.DB.Find(&store).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功",
			Data: store,
		}
		c.ServeJSON()
	}
}
func (c *StoreController) Up() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	address := c.GetString("address")
	tel := c.GetString("tel")
	id, _ := c.GetInt("id")
	store := models.Store{
		Name:    name,
		Address: address,
		Tel:     tel,
	}
	err := models.DB.Where("ID=?", id).Save(&store).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: store,
		}
		c.ServeJSON()
	}
}
